package com.sushuo.api.controller;

import java.util.Date;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sushuo.api.service.ProductService;
import com.sushuo.api.web.Result;
import com.sushuo.api.web.StatusCode;
import com.sushuo.api.web.error.ParamException;
import com.sushuo.base.bean.Product;
import com.sushuo.base.bean.sql.PageData;


@RequestMapping(value = "/product")
@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping(value = "/getById", produces = {"application/json;charset=UTF-8"})
    public Result getById(Integer id){
        Product product = productService.getById(id);
        return Result.success(product);
    }
    
    @RequestMapping(value = "/save", produces = {"application/json;charset=UTF-8"})
    public Result save(@Valid Product product){
        if(null == product.getGmtModified()) {
            product.setGmtModified(new Date());
        }
        Product p = productService.save(product);
        return Result.success(p);
    }

    @RequestMapping(value = "/deleteById", produces = {"application/json;charset=UTF-8"})
    public Result deleteById(Integer id){
        if (null == id) {
            throw new ParamException(StatusCode.PARAMTER.getValue(),"id must not be null");
        }
        try {
            productService.deleteById(id);
        }catch(EmptyResultDataAccessException e){
            throw new ParamException(StatusCode.PARAMTER.getValue(),"id not exist: " + id);
        }

        return new Result();
    }

    @RequestMapping(value = "/getPage", produces = {"application/json;charset=UTF-8"})
    public Result getPage(Integer page, Integer pageSize){
        if (null==page || page<=0 || null==pageSize || pageSize<=0) {
            throw new ParamException(StatusCode.PARAMTER.getValue(),"input param error");
        }
        PageData<Product> pData = productService.getPage(page, pageSize);
        return Result.success(pData);
    }
    
    @RequestMapping(value = "/getPageByUserId", produces = {"application/json;charset=UTF-8"})
    public Result getPageByUserId(Integer page, Integer pageSize, Integer userId){
        if(null==page || page<=0
                || null==pageSize || pageSize<=0
                || null==userId || userId<=0)
            throw new ParamException(StatusCode.PARAMTER.getValue(),"input param error");
        
        PageData<Product> pData = productService.getPageByUserId(page, pageSize, userId);
        return Result.success(pData);
    }
}
